package org.weixin4j.miniprogram.wxpay.sdk;

import com.rc.saas.mini.weixin.WxSessionInfo;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Create by Yang on 2021/5/27
 */
public class WXMyConfigUtil extends WXPayConfig {


    private WxSessionInfo wxSessionInfo;
    private byte[] certData;

    //从微信商户平台下载的安全证书存放的目录
    //public final String SDK_WX_REFUND_PATH ="wx.refund.path";

    public WXMyConfigUtil(WxSessionInfo wxSessionInfo) throws Exception {

        this.wxSessionInfo = wxSessionInfo;

        //拼接证书
        String certPath = WXPayConstants.WX_CERT_PREFIX + wxSessionInfo.getMchId() + WXPayConstants.WX_CERT_SUFFIX;

        //构造方法读取证书
        Resource resource = new ClassPathResource(certPath);
        InputStream certStream = resource.getInputStream();
        certData = new byte[(int) resource.getFile().length()];

        certStream.read(certData);
        certStream.close();

    }

    @Override
    String getAppID() {
        return wxSessionInfo.getAppId();
    }

    @Override
    String getMchID() {
        return wxSessionInfo.getMchId();
    }

    @Override
    String getKey() {
        return wxSessionInfo.getWechatPayMchid();
    }

    @Override
    InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    @Override
    IWXPayDomain getWXPayDomain() {
        IWXPayDomain iwxPayDomain = new IWXPayDomain() {
            @Override
            public void report(String domain, long elapsedTimeMillis, Exception ex) {

            }

            @Override
            public DomainInfo getDomain(WXPayConfig config) {
                return new DomainInfo(WXPayConstants.DOMAIN_API, true);
            }
        };
        return iwxPayDomain;
    }

    public static void main(String[] args) throws Exception {


        Resource resource = new ClassPathResource(WXPayConstants.WX_CERT_PATH);
        InputStream certStream = resource.getInputStream();
        byte[] certData = new byte[(int) resource.getFile().length()];
        InputStreamReader isr = new InputStreamReader(certStream);

        certStream.read(certData);
        certStream.close();

        //BufferedReader br = new BufferedReader(isr);
        //String data = null;
        for (byte certDatum : certData) {
            System.out.println(certDatum);
        }
        //while ((data = br.readLine()) != null) {
        //    System.out.println(data);
        //}

        certStream.close();
    }

    public WxSessionInfo getWxSessionInfo() {
        return wxSessionInfo;
    }

    public void setWxSessionInfo(WxSessionInfo wxSessionInfo) {
        this.wxSessionInfo = wxSessionInfo;
    }
}
